import { createRouter, createWebHistory } from "vue-router";
import HomeView from "../views/HomeView.vue";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      redirect: "home",
    },
    {
      path: "/home",
      name: "home",
      meta: {
        title: "首页",
      },
      component: HomeView,
    },
    {
      path: "/detail",
      name: "detail",
      meta: {
        title: "详情页",
      },
      component: () => import("../views/DetailView.vue"),
    },
    {
      path: "/cart",
      name: "cart",
      meta: {
        title: "购物车",
      },
      component: () => import("../views/CartView.vue"),
    },
    {
      path: "/mine",
      name: "mine",
      meta: {
        title: "我的",
      },
      component: () => import("../views/MineView.vue"),
    },
    {
      path: "/login",
      name: "login",
      meta: {
        title: "登录",
      },
      component: () => import("../views/LoginView.vue"),
    },
    {
      path: "/register",
      name: "register",
      meta: {
        title: "注册手机号",
      },
      component: () => import("../views/register/RegisterView.vue"),
    },
    {
      path: "/messagecode",
      name: "messagecode",
      meta: {
        title: "验证码",
      },
      component: () => import("../views/register/MessagecodeView.vue"),
    },
    {
      path: "/password",
      name: "password",
      meta: {
        title: "注册密码",
      },
      component: () => import("../views/register/PasswordView.vue"),
    },
    {
      path: "/search",
      name: "search",
      meta: {
        title: "搜索",
      },
      component: () => import("../views/SearchView.vue"),
    },
    {
      path: "/address",
      name: "address",
      meta: {
        title: "地址管理",
      },
      component: () => import("../views/AddressView.vue"),
    },

    {
      path: "/order",
      name: "order",
      meta: {
        title: "订单管理",
      },
      component: () => import("../views/OrderView.vue"),
    },
  ],
});

// 路由防跳
router.beforeEach((to, from) => {
  document.title = to.meta.title;
  if (to.fullPath === "/mine" || to.fullPath === "/cart") {
    if (localStorage.getItem("token")) {
      return true;
    } else {
      return { path: "/login" };
    }
  } else {
    return true;
  }
});
export default router;
